package com.hotlove.tools.common;

import java.io.*;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @Auther: hotlove_linx
 * @Date: 2022/4/16 18:00
 * @Description:
 */
public class MD5Util {
    private static MessageDigest digest;

    static {

        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public synchronized static String encrypt(String toEncrypt) {
        try {
            digest.update(toEncrypt.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] hash = digest.digest();

        return CommonUtils.bytes2Hex(hash);
    }

    public synchronized static String encryptList(List<?> list) {

        String toEncrypt = "";

        for (Object info : list) {
            toEncrypt += "-" + info;
        }

        try {
            digest.update(toEncrypt.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] hash = digest.digest();

        return CommonUtils.bytes2Hex(hash);
    }

    public synchronized static byte[] hash(String toEncrypt) {
        try {
            digest.update(toEncrypt.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] hash = digest.digest();
        return hash;
    }

    /**
     * MD5签名
     *
     * @param file
     * @return
     */
    public synchronized static String getFileMd5(File file) throws IOException {
        // 缓冲区大小（这个可以抽出一个参数）
        int bufferSize = 256 * 1024;
        BufferedInputStream bis = null;
        DigestInputStream digestInputStream = null;
        try {
            // 拿到一个MD5转换器（同样，这里可以换成SHA1）
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 使用DigestInputStream
            bis = new BufferedInputStream(new FileInputStream(file));
            digestInputStream = new DigestInputStream(bis, messageDigest);
            // read的过程中进行MD5处理，直到读完文件
            byte[] buffer = new byte[bufferSize];
            while (digestInputStream.read(buffer) > 0)
                ;
            // 获取最终的MessageDigest
            messageDigest = digestInputStream.getMessageDigest();
            // 拿到结果，也是字节数组，包含16个元素
            byte[] resultByteArray = messageDigest.digest();
            // 同样，把字节数组转换成字符串
            return CommonUtils.bytes2Hex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            return null;
        } finally {
            try {
                digestInputStream.close();
            } catch (Exception e) {
            }
            try {
                bis.close();
            } catch (Exception e) {
            }
        }
    }

}
